import React from 'react';
import ReactDOM from 'react-dom';
import mirror, {actions, connect} from 'mirrorx';
import { FormattedMessage } from 'react-intl';
import { Picker, List, DatePicker,Checkbox, Flex, Icon,Carousel} from 'antd-mobile';
import  PickerDom from '../../component/picker';

const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;
const ListItem = List.Item;
const goodId = T.urlQuery('goodId');

class App extends React.Component { 
    
	constructor(props) {
		super(props);
        this.state={
            isShowPannel:false,
            planList:[],
            activeId:0,
            contentActiveId:0,   
            showMore:false,
            index:0,
            down:false,
            planName:'',
            bannerUrl:"",
            campaignId:0,
            isAgree:false,
            imgHeight:'auto'
        };      
	}

	componentDidMount(){
        if(T.urlQuery('goodId') == 23 || T.urlQuery('goodId') == 22){ //如果goodid是23就重定向頁面
            actions.routing.push({
                pathname:"product-detail-tail",
                search:"?goodId=23"
            })
        }
        if(T.urlQuery("demoauto")){
            T.loginAction(()=>{
                this.requestPlanList(T.urlQuery('goodId')); //请求商品计划列表   
            });
        }else{
            this.requestPlanList(T.urlQuery('goodId')); //请求商品计划列表   
        }
		     
        // 根据goodid 判断是哪个商品  13=ELA  14=ESA 15=HJK
        let bannerUrl = "";
         switch(T.urlQuery('goodId')){
            case '13':
                bannerUrl = "/assets/images/details/ELA.png";
                break;
             case '14':
                bannerUrl = "/assets/images/details/ESA.png";
                break;
             case '15':
                bannerUrl = "/assets/images/details/HJK.png";
                break;
        }  
        this.setState({ //頂部商品大圖
            bannerUrl:bannerUrl
        })   
    }

    requestPlanList=(goodId)=>{  // 获取计划列表信息 
            T.fetch({
                url:"/market/plans/list.json",
                data:{goodId:goodId},
                loading:true        
            }).then((res)=>{
                if(res.success){                   
                    var planList = res.value.goodPlanPackageResponseDTOList;       
                    console.log(planList);             
                    for(var i = 0; i < planList.length; i++){ 
                        if(planList[i].goodsLayoutResponseDTO){
                            let claim = planList[i].goodsLayoutResponseDTO.goodsClaimProcessResponseDTOList || [];
                            for(var k = 0; k<claim.length; k++){
                                let m = 0,
                                    n = 0,
                                    t = 0;  
                                    for (m = 0; m < claim.length; m++) {  
                                        for (n = 0; n < claim.length; n++) {  
                                            if (claim[m].seq <= claim[n].seq) {                                          
                                                t = claim[m];  
                                                claim[m] = claim[n];  
                                                claim[n] = t;  
                                            }  
                                        }  
                                    }  
                            }
                            planList[i].goodsLayoutResponseDTO.goodsClaimProcessResponseDTOList = claim;
                        }
                        if(planList[i].goodsLayoutResponseDTO){
                            if(planList[i].goodsLayoutResponseDTO.goodsMediaResponseDTOList)
                            for(var j = 0; j<planList[i].goodsLayoutResponseDTO.goodsMediaResponseDTOList.length;j++){
                            let media = planList[i].goodsLayoutResponseDTO.goodsMediaResponseDTOList[j].mediaResponseDTOList; 
                            var m = 0,
                                n = 0,
                                t = 0;  
                                for (m = 0; m < media.length; m++) {  
                                    for (n = 0; n < media.length; n++) {  
                                        if (media[m].orderNo <= media[n].orderNo) {                                          
                                            t = media[m];  
                                            media[m] = media[n];  
                                            media[n] = t;  
                                        }  
                                    }  
                                }                           
                            planList[i].goodsLayoutResponseDTO.goodsMediaResponseDTOList[j].mediaResponseDTOList = media;
                            } 
                        }                   
                        
                    }       
                    this.setState({
                        planList:planList,
                        activeId:res.value.goodPlanPackageResponseDTOList[0].planSingleResponseDTO.id,
                        planName:res.value.goodPlanPackageResponseDTOList[0].planSingleResponseDTO.planName,
                        productPackageId:res.value.goodPlanPackageResponseDTOList[0].productPackageId,
                        campaignId:res.value.goodPlanPackageResponseDTOList[0].campaignId                                                            
                    })          
                    if(res.value.goodPlanPackageResponseDTOList[0].agreementResponseDTO) {
                        this.setState({                      
                        agreementResponseDTO:res.value.goodPlanPackageResponseDTOList[0].agreementResponseDTO.notice  || ""                                       
                    })    
                    }        
                    this.dealPlanTabs(res.value.goodPlanPackageResponseDTOList);
                    //sessionStorage.setItem("notice",res.value.goodPlanPackageResponseDTOList[0].agreementResponseDTO.notice);//notice 放缓存
                }
            })           
            
}
    dealPlanTabs=(planList)=>{ //初始化计划tab
        var tabs = [];
        for ( var i = 0; i<planList.length; i++){
            let obj = { 
                "productPackageId":planList[i].productPackageId,              
                "planId": planList[i].planSingleResponseDTO.id,
                "planName":planList[i].planSingleResponseDTO.planName,
                "campaignId":planList[i].campaignId,
                "agreementResponseDTO":planList[i].agreementResponseDTO,
                "value":"計畫"+(i+1)
            };
            tabs.push(obj);
        }  
        this.setState({
            tabs:tabs
        });     
        console.log("tabs");
        console.log(tabs);        
        if(T.urlQuery('goodId') == '108004'){           
            this.refs.picker.calPremium(this.refs.picker.state.pickval,'','','',this.refs.picker.state.staff); 
        }else{
            this.refs.picker.calPremium(this.refs.picker.state.pickval,this.refs.picker.state.date); 
        }
    }

  
    faqClick=(e)=>{ //点击显示和隐藏FAQ的答案
       let target = e.currentTarget;
       let index = target.getAttribute("data-index");     
       if(this.state.activeIndex == index){
            this.setState({
                activeIndex:index,
                down:!this.state.down
            }) 
       }else{
          this.setState({
                activeIndex:index,
                down:true
            })  
       }
       
    }
    showMoreLiability=(id)=>{ //点击查看更多     
        this.setState({showMore:true,pid:id});
        if(this.state.pid == id && this.state.showMore){
            T.showInfo("没有更多了");
        }       
    }  
    clickTab=(index)=>{//點擊頂部商品詳情 理賠流程等tab    
        setTimeout(function() {
            location.replace("#"+index)
        }, 100);  
        this.setState({contentActiveId:index})
        //console.log("000000");
    }
    applyNow=()=>{ //點擊彈出試算面板
       this.setState({isShowPannel:true});
       if(T.urlQuery('goodId') == '108004'){ 
            this.refs.picker.calPremium(this.refs.picker.state.pickval,'','','',this.refs.picker.state.staff); 
       }else{
            this.refs.picker.calPremium(this.refs.picker.state.pickval,this.refs.picker.state.date); 
       }            
    }
    clickPlanTab=(planId,planName,productPackageId,campaignId,agreementResponseDTO)=>{ //點擊切換計劃
        let notice = "";
        if(agreementResponseDTO){
            notice = agreementResponseDTO.notice
        }       
        this.setState({
            activeId:planId,
            planName:planName,
            productPackageId:productPackageId,
            campaignId:campaignId,
            agreementResponseDTO:notice 
        })  
            
    }
    toInsure=()=>{ //跳轉到投保   
        //請求健康告知，看是否有健康告知，有就跳轉到健康告知，沒有就跳轉到投保頁面    
        const packageId = this.state.productPackageId;
        if(!this.state.isAgree){//没勾选须知
            T.showError(window.LangMessage.check_agree_insure_protcol || "请勾选同意投保须知");         
        }else{
            var p1 =  T.fetch({
                url:"/market/health/inform.json",
                data:{packageId:packageId,groupType:"HOLDERINFORM"},
                loading:true        
            }).then((res)=>{
               return res;
            });
            var p2 =  T.fetch({
                url:"/market/health/inform.json",
                data:{packageId:packageId,groupType:"INSURANTINFORM"},
                loading:true        
            }).then((res)=>{               
               return res;
            });
            Promise.all([p1, p2]).then(values => { 
                console.log(values); 
                if(values[0].value || values[1].value){                   
                         actions.routing.push({//有健康告知就跳轉到健康告知
                            pathname:"healthPolicy",
                            search:"?goodId="+T.urlQuery('goodId')+"&packageId="+packageId+"&planId="+this.state.activeId+"&campaignId="+this.state.campaignId
                        })
                    }else{
                        actions.routing.push({//沒有健康告知就跳轉到投保頁面
                            pathname:T.urlQuery('goodId') == '108004' ? "insure4" : "insure",
                            search:"?goodId="+T.urlQuery('goodId')+"&packageId="+packageId+"&planId="+this.state.activeId+"&campaignId="+this.state.campaignId
                        })                    
                    }
            });    
           
              
        }
                 
    }
    getamount=(a)=>{  //獲取試算的保費     
           this.setState({
                amount:a
            })
        }
   
	
	render() {        
        console.log(this.state);
        const planList = this.state.planList;
        const calResultList = this.state.calResultList;
        const tabs = this.state.tabs;
        const contentTabList = [window.LangMessage.product_detail || "商品详情",window.LangMessage.claim_process || "理赔流程",window.LangMessage.FAQ ||"常见问题"]; 
        const trailHeight = T.urlQuery('goodId') == '108004' ? '90%' : '80%'; 
            
		return (<div className="product-info">
            <div className="main">
                <div className="insurance clearfix">
                    <div className="tabbar-box">
                        <ul className="tabbar fc0" id="insuranceTabbar">
                            {contentTabList && contentTabList.map((item,index)=>
                                <li key={index} className={this.state.contentActiveId == index ? "active" : ""} onClick={()=>this.clickTab(index)}>
                                {item}</li>
                            )} 
                        </ul>                        
                    </div>                   
                </div> 
                {planList && planList.map((item,index)=>
                    <div key={index} className={ this.state.activeId ==item.planSingleResponseDTO.id ? "show" : "none"} >
                        {item.goodsLayoutResponseDTO && 
                            <div>
                                {item.goodsLayoutResponseDTO.goodsMediaResponseDTOList && item.goodsLayoutResponseDTO.goodsMediaResponseDTOList.map((goodMedia,index)=>
                                    <div key={index}>
                                    {goodMedia.mediaCategory == "MASTER" && 
                                    <div>
                                    {/* <Carousel
                                            autoplay={true}
                                            infinite
                                            selectedIndex={0}
                                            beforeChange={(from, to) => console.log()}
                                            afterChange={index => console.log()}
                                            dots={false}
                                        >*/}
                                        {goodMedia.mediaResponseDTOList.map((mediaImg,index)=>                                                  
                                            <a
                                            key={index}
                                            href={'javascript:;'}
                                            style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
                                        >
                                            <img
                                                src={"/ajax/file/downLoadFile/"+mediaImg.url+".file"}
                                                alt=""
                                                style={{ width: '100%', verticalAlign: 'top' }}
                                                onLoad={() => {                                                        
                                                    window.dispatchEvent(new Event('resize'));
                                                    this.setState({ imgHeight: 'auto' });
                                                }}
                                            />
                                        </a>                                      
                                        )}
                                        {/* </Carousel>*/}
                                        </div>
                                    }                                           
                                    </div>                                        
                                    )}
                               </div>     
                          }
                    </div>
                )}
              
                <div className="plan-card">
                {T.urlQuery("goodId") != "108004" &&  
                    <div className="plans-top">
                        <ul className="tabbar" id="cardTabbar">
                        { tabs &&  tabs.map((item,index)=>  <li className={this.state.activeId == item.planId ? "tab fl selected" : "tab fl"} key={index} data-plan={index} 
                         onClick={()=>this.clickPlanTab(item.planId,item.planName,item.productPackageId,item.campaignId,item.agreementResponseDTO)}>
                                <p className="price fcw"><span className="sign"></span><em className="priceNum">{item.planName}</em></p>
                            </li>)}                         
                        </ul>
                    </div>
                }
                    <div className="plans-bottom">
                        <ul id="benefit">                        
                         {planList && planList.map((item,index)=>
                                <li key={index} className={ this.state.activeId ==item.planSingleResponseDTO.id ? "show" : "none"}>                               
                                <ul className="benefit" data-id={item.productPackageId}>
                                {item.splitGoodsResponseDTOS.map((sgrdto,index)=> 
                                    <div key={index}>   
                                    {sgrdto.productResponseDTOList.map((prdto,index)=>
                                        <div key={index}>
                                         {prdto.productFundList && prdto.productFundList.map((pll,index)=>                                          
                                                <div key={index}>
                                                    {index<3 &&
                                                        <li className="cell" key={index}>                                             
                                                            <div className="left fl f30">{pll.fundName}</div>
                                                            <div className="right fr f36">{pll.ratio * 100 +"%"}</div>
                                                            <div style={{clear:'both'}}> </div>
                                                        </li>
                                                    }   
                                                    {index>3 &&                                                    
                                                        <li className={this.state.showMore && item.productPackageId == this.state.pid ? 'cell show' : 'none'} key={index}>                                             
                                                                <div className="left fl f30">{pll.fundName}</div>
                                                                <div className="right fr f36">{pll.ratio * 100 +"%"}%</div>
                                                                <div style={{clear:'both'}}> </div>
                                                        </li>
                                                    }
                                                </div>                                            
                                            )}
                                        {(prdto.productLiabilityList && T.urlQuery("goodId") != "108004") && prdto.productLiabilityList.map((pll,index)=>                                          
                                                <div key={index}>
                                                    {index<3 &&
                                                        <li className="cell" key={index}>                                             
                                                            <div className="left fl f30">{pll.liabilityResponseDTO.liabilityName}</div>
                                                            <div className="right fr f36">{pll.sumInsured}</div>
                                                            <div style={{clear:'both'}}> </div>
                                                        </li>
                                                    }   
                                                    {index>3 &&                                                    
                                                        <li className={this.state.showMore && item.productPackageId == this.state.pid ? 'cell show' : 'none'} key={index}>                                             
                                                                <div className="left fl f30">{pll.liabilityResponseDTO.liabilityName}</div>
                                                                <div className="right fr f36">{pll.sumInsured}</div>
                                                                <div style={{clear:'both'}}> </div>
                                                        </li>
                                                    }
                                                </div>                                            
                                            )}
                                            {prdto.productLiabilityList.length>3 && 
                                                <div style={{textAlign:'center'}} onClick={()=>this.showMoreLiability(item.productPackageId)}>
                                                <p className="f28 fc6"><FormattedMessage id='scan_more' defaultMessage='查看更多' /></p>
                                                <Icon type="down" />
                                                </div>
                                            }
                                        </div>)}
                                    
                                </div>)}
                                {T.urlQuery("goodId") != "108004" &&
                                    <div className="bor-top">
                                        {item.planSingleResponseDTO.insuredPeriod &&
                                            <li className="cell">
                                                <div className="left fl f30"><FormattedMessage id='protect_period' defaultMessage='保障期限' /></div>
                                                <div className="right fr f36"><div dangerouslySetInnerHTML={{__html: item.planSingleResponseDTO.insuredPeriod}} /><span className="f24"></span></div> 
                                                <div style={{clear:'both'}}> </div>
                                            </li>}
                                        {item.planSingleResponseDTO.suitCrowd &&
                                           <li className="cell"> 
                                                <div className="left fl f30"><FormattedMessage id='suit_crowd' defaultMessage='适用人群' /></div>
                                                <div className="right fr f36"><div className="f24" dangerouslySetInnerHTML={{__html:item.planSingleResponseDTO.suitCrowd}} /><span className="f24"></span></div>
                                                <div style={{clear:'both'}}> </div>
                                            </li>}
                                        {item.planSingleResponseDTO.suitAge&&
                                            <li className="cell">
                                                <div className="left fl f30"><FormattedMessage id='suit_age' defaultMessage='适用年龄' /></div>
                                                <div className="right fr f36"><div dangerouslySetInnerHTML={{__html:item.planSingleResponseDTO.suitAge}} /><span className="f24"></span></div>
                                                <div style={{clear:'both'}}> </div>
                                            </li>}
                                    </div>
                                }
                                </ul>
                                <div className="detail">
                                  <div className="titleWrap" id="0">
                                    <div className="tit"><FormattedMessage id='product_detail' defaultMessage='商品详情' /></div>
                                    </div>
                                    {item.goodsLayoutResponseDTO && 
                                        <div>
                                            {item.goodsLayoutResponseDTO.goodsMediaResponseDTOList && item.goodsLayoutResponseDTO.goodsMediaResponseDTOList.map((goodMedia,index)=>
                                                <div key={index}>
                                                {goodMedia.mediaCategory == "GROUP" && 
                                                    <div>
                                                    {goodMedia.mediaResponseDTOList.map((mediaImg,index)=>                                        
                                                        <img key={index} src={"/ajax/file/downLoadFile/"+mediaImg.url+".file"}/>                                        
                                                    )}
                                                    </div>
                                                }                                           
                                                </div>                                        
                                            )}
                                        </div>
                                    }
                                    {item.goodsLayoutResponseDTO &&
                                        <div>
                                            {item.goodsLayoutResponseDTO.goodsClaimProcessResponseDTOList && 
                                                <div className="titleWrap pt20" id="1">
                                                        <div className="tit"><FormattedMessage id='claim_process' defaultMessage='理赔流程' /></div>
                                                </div>
                                            }  
                                        </div>
                                    } 
                                    <div className="claim-text">
                                        {item.goodsLayoutResponseDTO &&
                                            <div>
                                                {item.goodsLayoutResponseDTO.goodsClaimProcessResponseDTOList && item.goodsLayoutResponseDTO.goodsClaimProcessResponseDTOList.map((claim,index)=>
                                                
                                                <p key={index}  className="title f34 fc0 pl20 " dangerouslySetInnerHTML={{__html:index+1+'.'+claim.claimContent}}>
                                                                                               
                                                </p>                                                
                                                )}
                                            </div>
                                        }
                                     </div>  
                                     {item.goodsLayoutResponseDTO &&
                                         <div>
                                            {item.goodsLayoutResponseDTO.goodsFaqResponseDTOList && item.goodsLayoutResponseDTO.goodsFaqResponseDTOList.map((faq,index)=>
                                                <div key={index} className="FAQ">
                                                {index==0 && 
                                                    <div className="titleWrap  pt20" id="2">
                                                            <div className="tit"><FormattedMessage id='FAQ' defaultMessage='常见问题' /></div>
                                                        </div>
                                                }                                            
                                                    <div className={index+1 == item.goodsLayoutResponseDTO.goodsFaqResponseDTOList.length ? "cell" : "cell bor-bottom" }>
                                                        <p onClick={this.faqClick} className="title f34 fc0 pl20" data-index={index}>{faq.question}<span className={this.state.activeIndex==index && this.state.down ? "arrow arrow-up fr" : "arrow arrow-down fr"}  data-index={index}></span></p>
                                                        <div className={this.state.activeIndex==index && this.state.down ? "content f30 fc6" : "content f30 fc6 none"} data-index={index} dangerouslySetInnerHTML={{__html: faq.answer}}></div> 
                                                    </div> 
                                                                                        
                                                </div>                                        
                                            )}
                                        </div>
                                     }
                                </div>

                            </li>
                         )}                      
                           
                        </ul>
                    </div>
                </div>  
                <div className="footer ">              
                    <table>
                        <tbody>
                            <tr>
                                <td onClick={this.applyNow}>
                                    <a className="f38 fcw tac diy_background" >Apply Now
                                    </a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <div className={this.state.isShowAgreement ? "productNotice":"none"}>
                <div className="trial-wrap " >
                    <div className="clearfix bor-bottom pt30 pb30 pl30 pr30">
                        <p className="fl f30 strong" style={{width:'80%'}}><FormattedMessage id='insure_must_know' defaultMessage='投保须知' /></p>
                        <p className="fr" onClick={()=>this.setState({isShowAgreement:false})}><img className="closeTag close-tag" src="/assets/images/close1.png" /></p>
                    </div>                   
            </div>
             <div className="productNotice-text"><div dangerouslySetInnerHTML={{__html: this.state.agreementResponseDTO}} /></div>
                    
            </div>
            
            {/* 保费试算弹窗 */}
            <div className={"trial-pannel " + (this.state.isShowPannel?"":"none")}>
                <div className="trial-wrap" style={{height:trailHeight}} >
                    <div className="clearfix bor-bottom pt30 pb30 pl30 pr30">
                        <p className="fl f30 strong" style={{width:'80%'}}>{this.state.planName}</p>
                        <p className="fr" onClick={()=>this.setState({isShowPannel:false})}><img className="closeTag close-tag" src="/assets/images/close1.png" /></p>
                    </div>
                    {/* 试算因子 */}
                    <div className="trial-content pl20 pr20" style={{paddingBottom:1.5}}>
                         <PickerDom id={this.state.activeId} ref="picker"  getAmount={this.getamount}/>
                    </div>
                </div>
                <Flex style={{position:"fixed",bottom:"1.06rem"}}>
                    <Flex.Item>
                    <AgreeItem data-seed="logId" onChange={e => this.setState({isAgree:e.target.checked})}>
                        <FormattedMessage id='has_read' defaultMessage='我已阅读' /> <a className="diy_color" onClick={()=>this.setState({isShowAgreement:true})}>《<FormattedMessage id='insure_must_know' defaultMessage='投保须知' />》</a>
                    </AgreeItem>
                    </Flex.Item>
                </Flex>
                    
                <div className="footer">                
                    <table>
                        <tbody>
                            <tr>
                                <td>
                                {this.refs.picker &&
                                    <a className="f38 fc6 tac color-price">&nbsp;&nbsp;<span className="f30"></span><span id="totalMoney">{this.state.amount}</span>
                                    </a>
                                }
                                </td>
                                
                                <td width="40%">
                                    <a className="f32 fcw diy_background" id="applyBtn" onClick={this.toInsure}>Apply Now</a>
                                </td> 
                            </tr>
                        </tbody>
                    </table>
                </div>           
            </div>      
        </div>)
	}
}


export default App;   